<template>
  <div>
    <el-row type="flex">
      <el-button
        v-show="showBtn('设置价格组') && canOpeState"
        type="primary"
        :disabled="!(tableSelectData && tableSelectData.length > 0)"
        @click="handleSetPriceGroup"
      >设置价格组</el-button
      >
      <el-button
        v-show="showBtn('高级关联')"
        type="primary"
        icon="el-icon-link"
        @click="handleSeniorLinked"
      >高级关联</el-button
      >
    </el-row>
    <!--价格组设置-->
    <Modal
      v-model="setGroupVisible"
      title="价格组设置"
      width="100%"
      fullscreen
      :closable="false"
    >
      <el-card class="price_group_setting">
        <el-row type="flex" align="middle">
          <h3>组设置方式：</h3>
          <el-button type="primary" @click="handleSetGroup">组设置</el-button>
          <el-button
            v-if="hasGroupList"
            :loading="btnLoading.submit"
            type="primary"
            @click="handleSubmitByEndingStep"
          >提交</el-button>
        </el-row>
        <el-row>
          <BasicTable
            :showSelectCol="false"
            :showPagination="false"
            :dataSource="referGroup.list"
            :columns="referGroup.columns"
          />
        </el-row>
        <el-row v-if="singleTableData.length !== 0">
          <el-divider content-position="center"><i class="el-icon-price-tag"></i>单计量列表</el-divider>
          <BtnRender :render="(h) => { return renderBtnsBar(h, 'single') }" />
          <SkusTable
            ref="singleRef"
            :loading="loading.singleTable"
            :data-source="singleTableData"
            :columns="singleTableColumns"
            @handleRowChange="data => { handleRowChange(data, 'single') }"
            @handleCancelSelect="handleCancelSelect"
            :maxTableHeight="480"
          />
        </el-row>
        <el-row v-if="multipleTableData.length !== 0">
          <el-divider content-position="center"><i class="el-icon-price-tag"></i>多计量列表</el-divider>
          <BtnRender :render="(h) => { return renderBtnsBar(h, 'multiple') }" />
          <SkusTable
            ref="multipleRef"
            :loading="loading.multipleTable"
            :data-source="multipleTableData"
            :columns="multipleTableColumns"
            @handleRowChange="data => { handleRowChange(data, 'multiple') }"
            @handleCancelSelect="handleCancelSelect"
            :maxTableHeight="480"
          />
        </el-row>
      </el-card>
      <div slot="footer">
        <el-button @click="handleClosePGModal">取消</el-button>
      </div>
    </Modal>
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getResultBySeniorSearch"
    />
    <PriceGroupSettingDialog
      :pageName="referGroup.pageName"
      :groupVisible.sync="referGroup.visible"
      :productUuids="productUuids"
      @getSubmitReferGroupResult="getSubmitReferGroupResult"
    />
    <ViewOriginalPriceGroupDialog
      :visible.sync="viewPriceGroup.visible"
      :originalParams="viewPriceGroup.params"
    />
  </div>
</template>
<script>
import dynamictablebtns from '@/mixins/dynamictablebtns'; // 混入通用代码
import { mapGetters } from 'vuex';
// import { judgeAuthDepartmentFn } from '@/pages/commodity/modules/utils';
import BtnRender from '@/components/JSXRender/BtnRender';
import SkusTable from '@/pages/commodity/modules/components/saleSkusTable';
import BasicTable from '@/components/BasicTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import ViewOriginalPriceGroupDialog from '@/components/common/dialog/priceGroupSetDialog/viewOriginalPriceGroupDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import PriceGroupSettingDialog from '@/pages/commodity/components/PriceGroupSettingDialog';
import {
  getSinglePriceGroupColumnsFn,
  getMultiplePriceGroupColumnsFn
} from '@/pages/commodity/modules/constants/salePriceGroupModule/editModule';
import {
  errorsColumn,
  tipsColumn,
  hasErrorsByUnSubmit,
  hasTipsByWarning,
  getTableDataByJoinStr
} from '@/utils/priceValidate';
import { getBtnsBar } from '@/utils/getBtnsRender';
import {
  isResponseSuccessState,
  generateUuid,
  createExcelByExport,
  setAuthBtnId
} from '@/utils/bizUtils';
import {
  exportSaleTemplateService,
  deleteExportUuidService,
  countSinglePriceService
} from '@/api/finance/common/salePrice';
import {
  getInitByProductUuidsService,
  getNewByProductUuidsService,
  getSetGroupListService,
  submitPriceRelativeInfoService,
  validatePriceRelativeInfoService
} from '@/api/finance/salePriceManage/editSalePriceGroup';
import { EDIT_PRICE_GROUP_AMOUNT } from '@/constants/exportAmountLimit';
import { SALE_PAGE_NAMES, ENUM_TEXT_MAPS } from '@/constants/commodity';
import { getCanOpeState } from '@/utils/getUtils';

export default {
  mixins: [dynamictablebtns],
  components: {
    SkusTable,
    ViewOriginalPriceGroupDialog,
    SeniorLinkedDialog,
    BtnRender,
    PriceGroupSettingDialog,
    BasicTable,
    FooterFields
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      productUuids: [], // 展示列表勾选spu的productUuid编码集合
      setGroupVisible: false, // 全屏modal弹框开关
      // 高级关联
      seniorLinked: {
        visible: false,
        columns: [{
          label: 'SPU编码',
          prop: 'spuNo',
          type: 'textarea'
        }],
        dataSource: [{ spuNo: '' }]
      },
      // 查看价格组
      viewPriceGroup: {
        params: {},
        visible: false,
      },
      // 价格组参照关系
      referGroup: {
        list: [], // 已设置价格组列表
        columns: [ // 展示表格columns
          { title: '组名称', key: 'groupName' },
          { title: '主城市', key: 'mainCity' },
          { title: '参照省组', key: 'mainGroupName' },
          { title: '价格比例', key: 'rate' },
          {
            title: '包含城市',
            render: (h, { row }) => <span>{row.provinceNameList.join(',')}</span>
          },
        ],
        pageName: SALE_PAGE_NAMES.EDIT_GROUP, // 页面名称（用以价格组设置弹框判断对应接口调用）
        visible: false // 组设置弹框显隐开关
      },
      // 单计量表格
      singleTableData: [],
      singleTableDataClone: [],
      singleTableColumns: [],
      // 多计量表格
      multipleTableData: [],
      multipleTableDataClone: [],
      multipleTableColumns: [],
      // 表格loading
      loading: {
        singleTable: false,
        multipleTable: false
      },
      submitUuid: '', // 提交所需uuid（前端生成）
      // 导出所需uuid（前端生成）
      exportUuid: {
        single: '',
        multiple: ''
      },
      // 按钮loading
      btnLoading: {
        singleExport: false,
        multipleExport: false,
        submit: false
      },
    };
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    // 有已经设置的价格组
    hasGroupList () {
      return this.referGroup.list.length > 0;
    }
  },
  mounted () {
    this.setCanOpeState()
    this.initTableColumns();
  },
  methods: {
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    renderBtnsBar (h, type) {
      const importUrls = {
        'single': 'sysback/salepirce/up/excel/importSingleUnit',
        'multiple': 'sysback/salepirce/up/excel/importMultiUnit'
      }
      const btns = [
        {
          label: '模板导入',
          action: importUrls[type],
          methods: { handleUploadSuccess: (res) => { this.handleUploadSuccess(res, type) } },
          isImport: true,
          loadingFn: state => { this.loading[`${type}Table`] = state }
        },
        {
          label: '模板导出',
          method: () => { this.handleExportTemplate(type) },
          loading: this.btnLoading[`${type}Export`],
          size: 'large'
        },
      ]
      return getBtnsBar(h, btns);
    },
    // 模板导入成功
    handleUploadSuccess (res, type) {
      this.loading[`${type}Table`] = false;
      if (isResponseSuccessState(res.retStatus)) {
        if (type === 'single' && res.retData[0].nowInput.isSaleMultiUnit === '1') {
          return this.$message.warning('请导入单计量列表');
        }
        if (type === 'multiple' && res.retData[0].nowInput.isSaleMultiUnit !== '1') {
          return this.$message.warning('请导入多计量列表');
        }
        this[`${type}TableData`] = res.retData;
        this[`${type}TableDataClone`] = _.cloneDeep(this[`${type}TableData`]);
      } else {
        this.$message.error(res.retMessage);
      }
    },
    // 模板导出
    handleExportTemplate (type) {
      // type首字母是大写，所以先转小写再传
      this.exportTemplateData(type);
    },
    // 模板数据导出
    async exportTemplateData (type) {
      const unitByTypes = {
        'single': { unitType: '2', label: '单计量' },
        'multiple': { unitType: '1', label: '多计量' }
      }
      const isSaleMultiUnit = unitByTypes[type]?.unitType;
      const label = unitByTypes[type].label;
      this.exportUuid[type] = generateUuid();
      const data = {
        uuid: this.exportUuid[type],
        isSaleMultiUnit,
        tableData: this[`${type}TableData`]
      }
      const res = await exportSaleTemplateService(data, state => { this.btnLoading[`${type}Export`] = state; });
      createExcelByExport({ res, excelTitle: `售价价格组-${label}_${this.exportUuid[type]}` });
    },
    initTableColumns () {
      this.singleTableColumns = _.cloneDeep(
        getSinglePriceGroupColumnsFn({
          handleViewOriginalPriceGroup: this.handleViewOriginalPriceGroup
        })
      );
      this.multipleTableColumns = _.cloneDeep(
        getMultiplePriceGroupColumnsFn({
          handleViewOriginalPriceGroup: this.handleViewOriginalPriceGroup
        })
      );
    },
    // 获取高级查询结果-by 高级关联
    getResultBySeniorSearch (spuNos) {
      this.$emit('getSpuNosBySeniorLinked', spuNos);
    },
    // 高级关联
    handleSeniorLinked () {
      setAuthBtnId('高级关联');
      this.seniorLinked.visible = true;
    },
    // 重置数据
    resetProductUuidRelativeData () {
      this.referGroup.list = [];
      this.singleTableData = [];
      this.singleTableDataClone = [];
      this.multipleTableData = [];
      this.multipleTableDataClone = [];
    },
    // 设置productUuid相关数据
    setProductUuidRelativeData (data) {
      this.singleTableData = data.upInputList; // 单计量
      this.singleTableDataClone = _.cloneDeep(this.singleTableData);
      this.multipleTableData = data.upSteelInputList; // 多计量
      this.multipleTableDataClone = _.cloneDeep(this.multipleTableData);
      this.productUuids = data.productUuids; // 存储uuid数组
    },
    // 设置价格组
    async handleSetPriceGroup () {
      // const isSuccessed = judgeAuthDepartmentFn(this.tableSelectData); // 验归属部门方法
      // if (!isSuccessed) { return false; }
      this.resetProductUuidRelativeData();
      this.setGroupVisible = true;
      const productUuids = this.tableSelectData.map(item => item.productUuid);
      const retData = await getInitByProductUuidsService(
        productUuids, '.price_group_setting'
      );
      if (retData) {
        this.setProductUuidRelativeData(retData);
      }
    },
    // 设置组
    handleSetGroup () {
      this.referGroup.visible = true;
    },
    // 获取设置后的价格组参照关系的提交结果
    async getSubmitReferGroupResult ({ uuid }) {
      this.submitUuid = uuid;
      const isSuccessTable = await this.reloadTableData();
      if (!isSuccessTable) { return false; }
      const isSuccessedGroup = this.getReferGroupInfo();
      if (isSuccessedGroup) {
        this.setGroupVisible = true;
      }
    },
    // 重新请求加载表格数据
    async reloadTableData () {
      const params = {
        uuid: this.submitUuid,
        data: this.productUuids
      }
      const retData = await getNewByProductUuidsService(params, '.price_group_setting');
      if (retData) {
        this.setProductUuidRelativeData(retData);
        return true;
      }
      return false;
    },
    // 获取参照组信息
    async getReferGroupInfo () {
      const data = { uuid: this.submitUuid }
      const retData = await getSetGroupListService(data, '.price_group_setting');
      if (retData) {
        this.referGroup.list = retData;
        return true;
      }
      return false;
    },
    // 查看原价格组
    handleViewOriginalPriceGroup (row) {
      this.viewPriceGroup.params = {
        data: {
          productUuid: row.productUuid,
        },
        url: `${this.requestApi.getContainCoverageByProductUuid.url}?productUuid=${row.productUuid}`,
        type: this.requestApi.getContainCoverageByProductUuid.type
      };
      this.viewPriceGroup.visible = true;
    },
    /**
     * 需要验证数据的时候
     * @data 由row, columnName(当前列名), index组成
     * @tableData 表格数据
     */
    /* 表格计算方法 */
    handleRowChange (data, type) {
      this.calculatePrice(data, type);
    },
    // 计算售价
    async calculatePrice (data, type) {
      const { row, columnName } = data;
      if (ENUM_TEXT_MAPS[columnName]) {
        row.enumTxtInput = ENUM_TEXT_MAPS[columnName];
      }
      const retData = await countSinglePriceService(
        row, state => { this.loading[`${type}Table`] = state }
      );
      this.resetPriceByCurrentRow({ ...data, type, retData });
    },
    // 重新设置当前行价格数据
    resetPriceByCurrentRow ({ row, columnName, index, type, retData }) {
      if (retData) {
        this.$data[`${type}TableData`] = this.$data[`${type}TableData`].map(
          item => (item.skuNo + item.cityCode) === (retData.skuNo + retData.cityCode) ? retData : item
        );
        this.$data[`${type}TableDataClone`] = _.cloneDeep(this.$data[`${type}TableData`]);
      } else {
        row.nowInput[columnName] = this.$data[`${type}TableDataClone`][index].nowInput[columnName];
      }
    },
    // 提交 by 最后一步
    handleSubmitByEndingStep () {
      const totalLength = this.singleTableData.length + this.multipleTableData.length;
      if (totalLength > EDIT_PRICE_GROUP_AMOUNT) {
        return this.$message.warning(`当前单据提交的行数不能超过${EDIT_PRICE_GROUP_AMOUNT}`)
      }
      this.validateBeforeSubmit();
    },
    // 获取提交入参
    getParamsBySubmit () {
      return {
        commitTypeStr: '1',
        t: {
          upInputList: this.singleTableData || [],
          upSteelInputList: this.multipleTableData || [],
          productUuids: this.productUuids,
          groupIsUpdate: '1',
          operType: '1'
        }
      }
    },
    // 获取更新后的表列
    getUpdateColumns (tableColumns, type) {
      const initColumns = _.cloneDeep(tableColumns).filter(item => !['unSubmitReason', 'abnormalTip'].includes(item.key));
      const tipsColumns = [tipsColumn, ...initColumns];
      const errsColumns = [errorsColumn, tipsColumn, ...initColumns];
      const columnsTypes = {
        'error': errsColumns,
        'tip': tipsColumns,
        'normal': initColumns
      }
      return columnsTypes[type] || [];
    },
    // 设置校验更新后的表格信息
    setTableInfoByValidate ({ upInputList, upSteelInputList, type }) {
      this.singleTableColumns = this.getUpdateColumns(this.singleTableColumns, type);
      this.multipleTableColumns = this.getUpdateColumns(this.multipleTableColumns, type);
      this.singleTableData = getTableDataByJoinStr(upInputList);
      this.multipleTableData = getTableDataByJoinStr(upSteelInputList);
    },
    // 禁止提交原因确认弹框
    openConfirmByUnSubmitReason () {
      this.$confirm(
        '存在禁止提交原因，无法提交单据，请在详情页中查看具体原因',
        '提交错误提示',
        { type: 'warning', showCancelButton: false }
      ).then(() => {}).catch(() => {});
    },
    // 异常提示确认弹框
    openConfirmByAbnormalTips () {
      this.$confirm(
        '存在异常提示，是否仍要提交？',
        '提交异常提示',
        { type: 'warning', cancelButtonText: '查看详情' }
      ).then(() => {
        this.submitPriceData();
      }).catch(() => {});
    },
    // 提交前校验
    async validateBeforeSubmit () {
      const params = {
        uuid: this.submitUuid,
        data: this.getParamsBySubmit()
      }
      const retData = await validatePriceRelativeInfoService(
        params, state => { this.btnLoading.submit = state }
      );
      if (!retData) { return false; }
      const { upInputList, upSteelInputList } = retData.t;
      const allInputList = _.cloneDeep(upInputList).concat(_.cloneDeep(upSteelInputList));
      if (hasErrorsByUnSubmit(allInputList)) {
        this.setTableInfoByValidate({ upInputList, upSteelInputList, type: 'error' });
        this.openConfirmByUnSubmitReason(retData.t);
        return false;
      }
      if (hasTipsByWarning(allInputList)) {
        this.setTableInfoByValidate({ upInputList, upSteelInputList, type: 'tip' });
        this.openConfirmByAbnormalTips(retData.t);
        return false;
      }
      this.setTableInfoByValidate({ upInputList, upSteelInputList, type: 'normal' });
      this.submitPriceData();
    },
    // 提交售价数据
    async submitPriceData () {
      const params = {
        uuid: this.submitUuid,
        data: this.getParamsBySubmit()
      }
      const retData = await submitPriceRelativeInfoService(
        params, state => { this.btnLoading.submit = state }
      );
      if (retData) {
        this.$message.success('提交成功');
        if (this.exportUuid.single) {
          deleteExportUuidService(this.exportUuid.single);
        }
        if (this.exportUuid.multiple) {
          deleteExportUuidService(this.exportUuid.multiple);
        }
        this.handleClosePGModal();
      }
    },
    // 每一行后面的取消按钮
    // 传入的productUuids参数减少取消那行的productUuid
    handleCancelSelect ({ row }) {
      if (this.productUuids.length === 1) {
        this.resetProductUuidRelativeData();
      } else {
        this.productUuids = this.productUuids.filter(item => item !== row.productUuid);
        this.reloadTableData();
      }
    },
    // 关闭弹框
    handleClosePGModal () {
      this.setGroupVisible = false;
      this.$emit('clearSelectedList');
      this.initTableColumns();
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-input-number-handler-wrap {
  display: none;
}
</style>
